We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Volt - $compiler->addFunction ( Custom function with the instance of the ControllerBase.php class )

-

Hi everyone! This is my first post on the forum.

Could you help me with this question of object-oriented programming in PhalconPHP?

service.php

$compiler->addFunction('myfunction',function($resolvedArgs,$exprArgs) use ($compiler){
    $arg = $compiler->expression($exprArgs[0]['expr']);
    return 'ControllerBase::myfunction('.$arg.')';
});

ControllerBase.php

public static function myfunction($myString){
    if ($this->session->has('mysession')) {
        return $myString;
    } else {
        return 'session not found';
    }
}

index.volt

<p>{{ myfunction('myString') }}<p>

Error message I'm getting:

Fatal error: Using $this when not in object context in ...app/controllers/ControllerBase.php

Error line: "if ($this->session->has('mysession')) {"

How to use the instance "$this->session" ( or any other method or property instantiated in ControllerBase.php ) in the function "$compiler->addFunction" ( service.php )?

-



93.7k
Accepted
answer
edited Mar '16

You declared myFunction in your controller as static, therefor you are not allowed to use $this inside.

Access DI like so:

public static function myfunction($myString) {
    $di = \Phalcon\DI::getDefault(); 
    if ($di->getSession()->has('mysession')) {
    .........

And welcome to the forum friend :)



973

-

Hi Nikolay, thanks for answering.

But I would like to use the functions that are in the "ControllerBase.php" class, I wouldn't want to write code within "service.php":

I thought I'd get something like:

 return 'ControllerBase::myfunction('.$arg.')';

How can I use a function within the "ControllerBase.php" class with all the running instance ($this) and then return some value?

Best regards,

Hal

-

Just check my example and modify your code.

PHP does not allow using $this inside static method.



973

-

I'm sorry, You're right! Thanks.

Best regards,

Hal

-